package org.jpropeller.ui.impl;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;

/**
 * A modal {@link JDialog} that is constructed using a 
 * component to be displayed.
 * The dialog will display this component in the center, 
 * with a button below it to close the
 * dialog. These will hide and dispose the dialog, returning control
 * to the code that displayed the dialog.
 * 
 * Note that the dialog should be used once only, and
 * a new dialog created for every prompt.
 */
public class CloseDialog extends JDialog {

	private Component component;
	private Frame owner;
	private final String closeString;
	
	/**
	 * Create an {@link CloseDialog}
	 * 
	 * @param component 	The {@link Component} to display in the
	 * 						dialog
	 * @param owner 		The frame that owns this dialog
	 * @param title 		The title of the dialog
	 * @param close			The text to display on close button 
	 */
	public CloseDialog(
			Component component, Frame owner, 
			String title, 
			String close) {
		super(owner, title, true);
		
		this.component = component;
		this.owner = owner;
		this.closeString = close;
		
		//Create UI
		getContentPane().add(buildUI());
		
		pack();
		
		setLocationRelativeTo(owner);
	}

	/**
	 * @return Entire dialog UI
	 */
	public Component buildUI() {
		JPanel panel = new JPanel(new BorderLayout());
		panel.add(component);
		panel.add(buildButtonPanel(), BorderLayout.SOUTH);
		return panel;
	}
	
	/**
	 * @return Panel with select/cancel buttons
	 */
	public Component buildButtonPanel() {
		JPanel panel = new JPanel();
		
		//Create button, when clicked this will set
		//the selected class as appropriate, and
		//hide the dialog if a valid selection has been made,
		JButton close = new JButton(closeString);
		close.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				closeDialog();
			}
		});
		panel.add(close);
		
		getRootPane().setDefaultButton(close);

		return panel;
	}

	/**
	 * Does the same as clicking close - dialog will be hidden and disposed
	 */
	private void closeDialog() {
		setVisible(false);
		getContentPane().removeAll();
		dispose();
	}
	
	/**
	 * Display the dialog.
	 * Note that the dialog will remain open and modal until
	 * close is clicked, at which point it will be hidden
	 * and disposed.
	 */
	public void displayDialog() {
		//This displays window in sensible position, and eliminates the 
		//irritating "flick" where the window appears for a tiny interval 
		//(or just causes screen to be greyed in that area) then moves to
		//another position.
		setLocationRelativeTo(owner);
		setVisible(true);
	}
}